<template>
  <el-dialog
    v-model="visible"
    :title="`客户 ${customerName} 评估`"
    width="600px"
    @close="handleClose"
  >
    <div class="customer-evaluation-dialog">
      <el-form
        ref="evaluationFormRef"
        :model="evaluationForm"
        :rules="evaluationFormRules"
        label-width="100px"
      >
        <el-form-item label="客户价值" prop="valueScore">
          <el-rate
            v-model="evaluationForm.valueScore"
            :max="5"
            allow-half
            show-score
            score-template="{value}分"
          />
          <div class="rate-description">
            客户带来的直接经济效益评估
          </div>
        </el-form-item>
        
        <el-form-item label="合作潜力" prop="potentialScore">
          <el-rate
            v-model="evaluationForm.potentialScore"
            :max="5"
            allow-half
            show-score
            score-template="{value}分"
          />
          <div class="rate-description">
            客户未来合作的可能性和增长空间
          </div>
        </el-form-item>
        
        <el-form-item label="满意度" prop="satisfactionScore">
          <el-rate
            v-model="evaluationForm.satisfactionScore"
            :max="5"
            allow-half
            show-score
            score-template="{value}分"
          />
          <div class="rate-description">
            客户对产品和服务的满意程度
          </div>
        </el-form-item>
        
        <el-form-item label="信用评级" prop="creditRating">
          <el-select v-model="evaluationForm.creditRating" style="width: 100%">
            <el-option label="AAA - 优秀" value="AAA" />
            <el-option label="AA - 良好" value="AA" />
            <el-option label="A - 一般" value="A" />
            <el-option label="BBB - 较差" value="BBB" />
            <el-option label="BB - 差" value="BB" />
            <el-option label="B - 很差" value="B" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="风险等级" prop="riskLevel">
          <el-select v-model="evaluationForm.riskLevel" style="width: 100%">
            <el-option label="低风险" value="low" />
            <el-option label="中风险" value="medium" />
            <el-option label="高风险" value="high" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="评估备注" prop="remark">
          <el-input 
            v-model="evaluationForm.remark" 
            type="textarea" 
            :rows="4"
            placeholder="请输入评估备注信息"
          />
        </el-form-item>
      </el-form>
    </div>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="saveEvaluation">保存评估</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { ElMessage, FormInstance, FormRules } from 'element-plus'
import { customerAPI } from '@/api/customer'

interface Props {
  modelValue: boolean
  customerId: string
  customerName: string
}

interface EvaluationForm {
  valueScore: number
  potentialScore: number
  satisfactionScore: number
  creditRating: string
  riskLevel: string
  remark: string
}

const props = defineProps<Props>()
const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
  (e: 'evaluation-saved'): void
}>()

// 响应式数据
const visible = ref(false)
const evaluationFormRef = ref<FormInstance>()

const evaluationForm = ref<EvaluationForm>({
  valueScore: 0,
  potentialScore: 0,
  satisfactionScore: 0,
  creditRating: 'A',
  riskLevel: 'low',
  remark: ''
})

const evaluationFormRules = ref<FormRules>({
  valueScore: [
    { required: true, message: '请输入客户价值评分', trigger: 'change' }
  ],
  potentialScore: [
    { required: true, message: '请输入合作潜力评分', trigger: 'change' }
  ],
  satisfactionScore: [
    { required: true, message: '请输入满意度评分', trigger: 'change' }
  ],
  creditRating: [
    { required: true, message: '请选择信用评级', trigger: 'change' }
  ],
  riskLevel: [
    { required: true, message: '请选择风险等级', trigger: 'change' }
  ]
})

// 监听modelValue变化
watch(
  () => props.modelValue,
  (newValue: boolean) => {
    visible.value = newValue
    if (newValue) {
      // 使用nextTick确保DOM更新后再加载数据
      setTimeout(() => {
        loadEvaluation()
      }, 0)
    }
  },
  { immediate: true }
)

// 监听visible变化
watch(visible, (newValue: boolean) => {
  emit('update:modelValue', newValue)
})

// 加载客户评估信息
const loadEvaluation = async (): Promise<void> => {
  try {
    const response: any = await customerAPI.getCustomerEvaluation(props.customerId)
    if (response) {
      evaluationForm.value = {
        valueScore: parseFloat(response.valueScore) || 0,
        potentialScore: parseFloat(response.potentialScore) || 0,
        satisfactionScore: parseFloat(response.satisfactionScore) || 0,
        creditRating: response.creditRating || 'A',
        riskLevel: response.riskLevel || 'low',
        remark: response.remark || ''
      }
    }
  } catch (error) {
    console.error('加载客户评估信息失败:', error)
    ElMessage.error('加载客户评估信息失败: ' + (error as Error).message)
  }
}

// 保存评估
const saveEvaluation = async (): Promise<void> => {
  if (!evaluationFormRef.value) return
  
  await evaluationFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        await customerAPI.updateCustomerEvaluation(props.customerId, evaluationForm.value)
        ElMessage.success('客户评估保存成功')
        emit('evaluation-saved')
        handleClose()
      } catch (error) {
        console.error('保存客户评估失败:', error)
        ElMessage.error('保存客户评估失败: ' + (error as Error).message)
      }
    }
  })
}

// 关闭对话框
const handleClose = (): void => {
  visible.value = false
}
</script>

<style scoped lang="scss">
.customer-evaluation-dialog {
  padding: 20px 0;
  
  .rate-description {
    font-size: 12px;
    color: #909399;
    margin-top: 5px;
  }
  
  :deep(.el-rate__icon) {
    font-size: 20px;
  }
  
  :deep(.el-rate__text) {
    font-size: 14px;
    margin-left: 8px;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>